

import React, { Component } from 'react';
import { Tabs, Button, Table, Divider, Modal, Form, Input, Icon, notification, Select, Card, Drawer, Row, Col } from 'antd';
import '@/assets/css/settings';
import QRCode from 'qrcode.react'
import * as APIService from '../../axios/api';
import { withRouter } from "react-router-dom";
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const FormItem = Form.Item;
//弹出通知提醒框
function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};
class App extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataSource: [],
			pagination: {
				current: 1,   //当前页
				pageSize: 10,   //每一页的条数
			},
			loading: false,
			visible: false,
			modalData: '',//选中的数据
			handleType: 0,// 修改1
			options: [],
			visible_two: false,
			visible_all: false,
			id: [],
			printBatchList: []
		}
	}

	componentDidMount() {
		this.fetch()
	}

	//分页查询
	fetch = () => {
		this.setState({ loading: true });
		APIService.findHighLevelRacks().then(data => {
			//const dataSource = data.data.data;
			//console.log(data.data.data)
			APIService.findBaseFluentRacks().then(data => {
				const dataSource = data.data.data;
				this.setState({
					dataSource: dataSource,
					loading: false
				})
			})
		})
	}

	//新增按钮取消
	handleCancel = e => {
		this.props.form.resetFields();
		this.setState({
			visible: false,
			visible_two: false,
			visible_all: false
		});
	};

	printAll = (data) => {
		//获取表格的点击行的值 赋给表单
		this.props.form.setFieldsValue({
			storageLocationCod_print: data.storageLocationCod,
		})

		this.setState({
			visible_all: true,
			modalData: data,
		})
	}

	showPrintModal = (data) => {
		//获取表格的点击行的值 赋给表单
		this.props.form.setFieldsValue({
			storageLocationCod_print: data.storageLocationCod,
		})

		this.setState({
			visible_two: true,
			modalData: data,
		})
	}

	print = (data) => {
		this.props.form.validateFields(['storageLocationCod_print', 'storageLocationName_print', 'id'], (err, values) => {
			if (!err) {
				console.log(values)
				const data = {}
				data.storageLocationCod = values.storageLocationCod_print
				data.storageLocationName = values.storageLocationName_print
				data.id = this.state.modalData.id
				const that = this;

				APIService.printBaseDepotManagements().then(data => {
					//console.log(data.data.data)
					this.setState({ printBatchList: data.data.data })
					new Promise(function (resolve) {
						resolve();
					}).then(() => {
						for (var i = 0; i < this.state.printBatchList.length; i++) {
							this.changeImg(i)
						}
					}).then(() => {
						var printInnerHTML = window.document.getElementById('billDetails').innerHTML;
						window.document.body.innerHTML = printInnerHTML
						window.print();
						window.location.reload();
					})

					that.handleCancel();
					// that.props.form.resetFields();
					that.fetch();
				})
			} else {
				console.log(err);
			}
		});
	}

	canvasToImage = (canvas) => {
		var image = new Image();
		// 指定格式 PNG 图片后缀可自定义
		image.src = canvas.toDataURL("image/png");
		image.style = "height:100%";
		return image;
	}
	changeImg = (i) => {
		var mycanvas = document.getElementsByTagName('canvas');
		console.log(mycanvas[i])
		var img = this.canvasToImage(mycanvas[i]);
		var ewmImg = document.getElementById('ewm' + i);
		ewmImg.append(img);
		console.log(ewmImg)
	}

	// 修改
	submitAdd = (e) => {
		this.props.form.validateFields(['storageLocationCod', 'supplierCode', 'materialName', 'minimumStockQuantity', 'safetyStock', 'theHighestInventory', 'boxNumber', 'purchaseOrderType', 'materialCode', 'id', 'storageLocationLong', 'storageLocationWide', 'storageLocationHigh', 'peakLoad'], (err, values) => {
			if (!err) {
				values = Object.assign({}, values, { storageLocationCod: this.state.modalData.storageLocationCod, boxNumber: this.state.modalData.boxNumber, purchaseOrderType: this.state.modalData.purchaseOrderType, id: this.state.modalData.id, storageLocationLong: this.state.modalData.storageLocationLong, storageLocationWide: this.state.modalData.storageLocationWide, storageLocationHigh: this.state.modalData.storageLocationHigh, peakLoad: this.state.modalData.peakLoad })

				const that = this;
				APIService.updateBaseFluentRack(values).then(data => {
					if (data.data.code === 200) {
						openNotification('success', '操作成功')
					} else {
						openNotification('warning', data.data.msg)
					}
					that.handleCancel();
					that.props.form.resetFields();
					that.setState({
						visible: false,
					});
					that.fetch('');
				})
			}
		}
		);
	}

	onExpand = (record, index, indent, expanded) => { }

	//  1修改
	showModal = (data, type) => {
		if (type === 1) {
			this.props.form.setFieldsValue({
				id: data.id,
				purchaseOrderType: data.purchaseOrderType,
				materialCode: data.materialCode,
				boxNumber: data.boxNumber,
				storageLocationName: data.storageLocationName,
				materialName: data.materialName,
				supplierCode: data.supplierCode,
				minimumStockQuantity: data.minimumStockQuantity,
				safetyStock: data.safetyStock,
				storageLocationCod: data.storageLocationCod,
				theHighestInventory: data.theHighestInventory,
				storageLocationLong: data.storageLocationLong,
				storageLocationWide: data.storageLocationWide,
				storageLocationHigh: data.storageLocationHigh,
				peakLoad: data.peakLoad
			})
		}

		this.setState({
			visible: true,
			modalData: data,
			handleType: type,
			id: data.id,
		});
	};

	showDrawer = () => {
		this.setState({
			visible: true,
		});
	};

	onClose = () => {
		this.setState({
			visible: false,
		});
	};

	//查询
	handleSearch = (e) => {
    this.props.form.validateFields(['storageLocationCode', 'supplierCod'], (err, values) => {
      if (values.storageLocationCode === undefined) {
        values.storageLocationCode='';
      }
      if (values.supplierCod === undefined) {
        values.supplierCod='';
			}
			var json = {storageLocationCod:values.storageLocationCode,supplierCode:values.supplierCod}
      APIService.findShelvesByQuery(json).then(data => {
        const dataSource = data.data.data;
        console.log(dataSource)
        this.setState({
          dataSource: dataSource
        })
      })
    });
  };

	render() {
		const data = this.state.dataSource
		const { getFieldDecorator } = this.props.form;
		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
		}
		const columns = [

			{
				title: '编码',
				dataIndex: 'storageLocationCod',
			},

			{
				title: '存放物料名称',
				dataIndex: 'materialName',
			},

			{
				title: '物料编码',
				dataIndex: 'materialCode',
			},

			{
				title: '采购订单类型',
				dataIndex: 'purchaseOrderType',
			},

			{
				title: '盒子数量',
				dataIndex: 'boxNumber',
			},

			{
				title: '供应商编码',
				dataIndex: 'supplierCode',
			},

			{
				title: '最低库存量',
				dataIndex: 'minimumStockQuantity',
			},

			{
				title: '安全库存量',
				dataIndex: 'safetyStock',
			},

			{
				title: '最高库存量',
				dataIndex: 'theHighestInventory',
			},

			{
				title: '长',
				dataIndex: 'storageLocationLong',
			},

			{
				title: '宽',
				dataIndex: 'storageLocationWide',
			},

			{
				title: '高',
				dataIndex: 'storageLocationHigh',
			},

			{
				title: '最多载重',
				dataIndex: 'peakLoad',
			},

			{
				title: '操作',
				width: '12%',
				render: (text, record) => {
					return <span>
						<a onClick={() => this.showModal(record, 1)}>修改</a>
						<Divider type="vertical" />
						<a onClick={() => this.showPrintModal(record)}>打印</a>
					</span>
				}
			}
		]

		var operations = <div className="mydiv" > <Button icon="plus" onClick={() => this.print([], 0)} type="primary" > 批量打印 </Button></div >

		return (
			<div className="shadow-radius">

				<Form className="search-form" style={{ paddingBottom: 0 }}>
					<Row gutter={24}>
						<Col span={4}>
							<FormItem label="储位编码">
								{getFieldDecorator('storageLocationCode')(
									<Input placeholder='请输入储位编码' />
								)}
							</FormItem>
						</Col>
						<Col span={4}>
							<FormItem label="供应商编码">
							{getFieldDecorator('supplierCod')(
									<Input placeholder='请输入供应商编码' />
								)}
							</FormItem>
						</Col>
						<Col span={2} style={{ marginRight: '10px', display: 'flex' }} className="serarch-btns">
							<FormItem>
								<Button icon="search" type="primary" htmlType="submit" className={'btn'} onClick={this.handleSearch}>
									查询
								</Button>
							</FormItem>
						</Col>
					</Row>
				</Form>

				<Tabs defaultActiveKey="1" tabBarExtraContent={operations}>
					<TabPane tab={<span><Icon type="table" /><strong>货架详情</strong> </span>} key="1" >
						<Table columns={columns} dataSource={data} pagination={false} loading={this.state.loading} onExpand={(expanded, record) => this.onExpand(expanded, record)} rowKey={record => record.id} />
					</TabPane>
				</Tabs>

				<Drawer
					width='720px'
					title="修改"
					visible={this.state.visible}
					centered
					onOk={this.submitAdd}
					onCancel={this.handleCancel}
					onClose={this.onClose}
					bodyStyle={{ paddingBottom: 80 }}
				>
					<Form layout="vertical" hideRequiredMark>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="编码">
									{getFieldDecorator('storageLocationCod', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="存放物料名称">
									{getFieldDecorator('materialName', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="存放物料编码">
									{getFieldDecorator('materialCode', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="采购订单类型">
									{getFieldDecorator('purchaseOrderType', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="盒子数量">
									{getFieldDecorator('boxNumber', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="供应商编码">
									{getFieldDecorator('supplierCode', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="最低库存量">
									{getFieldDecorator('minimumStockQuantity', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="安全库存量">
									{getFieldDecorator('safetyStock', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="最高库存量">
									{getFieldDecorator('theHighestInventory', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="长">
									{getFieldDecorator('storageLocationLong', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="宽">
									{getFieldDecorator('storageLocationWide', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="高">
									{getFieldDecorator('storageLocationHigh', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="最多载重">
									{getFieldDecorator('peakLoad', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>
					</Form>

					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.onClose} style={{ marginRight: 8 }}>
							取消
            </Button>
						<Button onClick={this.submitAdd} type="primary">
							保存
            </Button>
					</div>

				</Drawer>

				<Modal
					width='600px'
					title="新增批号："
					visible={this.state.visible_two}
					centered
					onOk={() => { this.print() }}
					onCancel={() => this.handleCancel(0)}
					okText="打印"
					cancelText="取消"
					footer={null}
				>
					<Form {...formItemLayout_addMenu} >
						<Row gutter={26}>
							<Col span={12}>
								<FormItem label="编码：">
									{getFieldDecorator('storageLocationCod_print', {
									})(<Input placeholder="编码" disabled />)}
								</FormItem>
							</Col>
							<Col span={12}>
								<FormItem label="货架名称">
									{getFieldDecorator('storageLocationName_print', {})
										(<Select style={{ width: 120 }}  >
											<Option value="low">流离货架</Option>
											<Option value="high">高位货架</Option>
										</Select>)
									}
								</FormItem>
							</Col>
						</Row>
						<Row gutter={26}>
							<span>
								<Button onClick={() => { this.print() }} style={{ marginLeft: '43%' }} type="primary">打印</Button>
							</span>
						</Row>

					</Form>
				</Modal>

				<div id={"billDetails"}>
					{this.state.printBatchList.map((e, i) => {
						return <div className='cardStyle' id={'cardStyle' + i} style={{ display: 'block', width: '100%', padding: 0 }} key={i}>
							<Card style={{ padding: '0' }} className="card" title={
								<Row style={{ height: '80px' }} >
									<QRCode className="qrcode"
										value={e.storageLocationCod}  //value参数为生成二维码的链接
										size={80} //二维码的宽高尺寸
										fgColor="#000000"  //二维码的颜色
										style={{ display: 'none' }} />
									<div className="codeImg qrcode" id={"ewm" + i}></div>
									<Col span={8} className="name">物料名称:{e.storageLocationName}</Col>
									<Col span={8} className="code">物料编号:{e.storageLocationCod}</Col>
								</Row>
							} >
							</Card>
						</div>
					})}
				</div>


			</div>
		)
	}
}
export default Form.create()(withRouter(App));